<template>
  <el-card class="page-container">
    <template #header>
      <div class="header">
        <span>地图服务列表</span>
        <el-button type="primary" :icon="Plus" @click="openPublishDrawer">
          发布地图服务
        </el-button>
      </div>
    </template>
    <!-- 新增：查询表单 -->
    <el-form inline :model="queryForm" class="query-form" style="margin-bottom: 20px;">
      <el-form-item label="区域">
        <el-select v-model="queryForm.area" placeholder="请选择区域">
          <el-option label="哈达湾" value="hadawan"></el-option>
          <el-option label="鸟岛" value="niaodao"></el-option>
          <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
          <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
          <el-option label="泉湾" value="quanwan"></el-option>
          <el-option label="黑马河口" value="heimahekou"></el-option>
          <el-option label="二郎剑" value="erlangjian"></el-option>
          <el-option label="青海湖" value="qinghaihu"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="日期">
        <el-date-picker
            v-model="queryForm.date"
            type="date"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            placeholder="请选择日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleQuery">查询</el-button>
        <el-button @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 地图服务表格 -->
    <el-table
        v-loading="loading"
        :data="layerList"
        border
        style="width: 100%; margin-bottom: 20px"
    >
      <el-table-column
          prop="id"
          label="ID"
          width="80"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="date"
          label="日期"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="type"
          label="数据源类型"
          width="120"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="area"
          label="区域"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="wmsUrl"
          label="WMS地址"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="layerName"
          label="图层名称"
          align="center"
      ></el-table-column>
      <el-table-column
          prop="folderType"
          label="文件夹类型"
          width="120"
          align="center"
      ></el-table-column>
      <!-- 在表格中添加操作列 -->
      <el-table-column
          label="操作"
          width="180"
          align="center"
      >
        <template #default="scope">
<!--          <el-button :icon="Edit" circle plain type="success" @click="handleEdit(scope.row)"></el-button>-->
          <el-button :icon="View" circle plain type="primary" @click="handleView(scope.row)"></el-button>
          <el-button :icon="Delete" circle plain type="danger" @click="handleDelete(scope.row)"></el-button>
        </template>
      </el-table-column>
<!--      <el-table-column-->
<!--          label="操作"-->
<!--          width="180"-->
<!--          align="center"-->
<!--      >-->
<!--        <template #default="scope">-->
<!--          <el-button type="text" size="small">查看</el-button>-->
<!--          <el-button type="text" size="small">编辑</el-button>-->
<!--          <el-button type="text" size="small" style="color: #ff4d4f">删除</el-button>-->
<!--        </template>-->
<!--      </el-table-column>-->
    </el-table>

    <!-- 分页控件 -->
    <el-pagination
        @size-change="handleSizeChange"
        @current-change="handlePageChange"
        :current-page="currentPage"
        :page-sizes="[5, 10, 20]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
    ></el-pagination>
    <el-drawer
        v-model="publishDrawer"
        title="发布地图服务"
        direction="rtl"
        size="50%"
    >
      <el-form
          ref="publishFormRef"
          :model="formData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <!-- 日期选择 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker
              v-model="formData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
          ></el-date-picker>
        </el-form-item>

        <!-- 类型选择 -->
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="formData.type" placeholder="请选择类型">
            <el-option label="卫星数据" value="satellite"></el-option>
            <el-option label="无人机数据" value="drone"></el-option>
          </el-select>
        </el-form-item>

        <!-- 区域选择（条件显示：仅无人机类型需要） -->
        <el-form-item v-if="formData.type === 'drone'" label="区域" prop="area">
          <el-select v-model="formData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
            <el-option label="二郎剑" value="erlangjian"></el-option>
          </el-select>
        </el-form-item>

        <!-- 提交按钮 -->
        <el-form-item>
          <el-button type="primary" @click="handlePublish">发布</el-button>
          <el-button @click="publishDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
        v-model="editDrawer"
        title="编辑地图服务"
        direction="rtl"
        size="50%"
    >
      <el-form
          ref="editFormRef"
          :model="editFormData"
          :rules="rules"
          label-width="120px"
          size="large"
      >
        <el-form-item label="ID" prop="id" disabled>
          <el-input v-model="editFormData.id"></el-input>
        </el-form-item>
        <!-- 以下表单项与发布抽屉保持一致 -->
        <el-form-item label="日期" prop="date">
          <el-date-picker
              v-model="editFormData.date"
              type="date"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
              placeholder="请选择日期"
          ></el-date-picker>
        </el-form-item>
        <el-form-item label="数据源类型" prop="type">
          <el-select v-model="editFormData.type" placeholder="请选择类型">
            <el-option label="卫星数据" value="satellite"></el-option>
            <el-option label="无人机数据" value="drone"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item v-if="editFormData.type === 'drone'" label="区域" prop="area">
          <el-select v-model="editFormData.area" placeholder="请选择区域">
            <el-option label="哈达湾" value="hadawan"></el-option>
            <el-option label="鸟岛" value="niaodao"></el-option>
            <el-option label="布哈河口海北区" value="buhahekouhaibeiqu"></el-option>
            <el-option label="布哈河口海南区" value="buhahekouhainanqu"></el-option>
            <el-option label="泉湾" value="quanwan"></el-option>
            <el-option label="黑马河口" value="heimahekou"></el-option>
            <el-option label="二郎剑" value="erlangjian"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleUpdate">保存</el-button>
          <el-button @click="editDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-drawer>
    <el-drawer
        v-model="detailDrawer"
        title="地图服务详情"
        direction="rtl"
        size="50%"
    >
      <el-descriptions :column="1" border>
        <el-descriptions-item label="ID">{{ currentLayer.id }}</el-descriptions-item>
        <el-descriptions-item label="日期">{{ currentLayer.date }}</el-descriptions-item>
        <el-descriptions-item label="数据源类型">
          {{ currentLayer.type === 'satellite' ? '卫星数据' : '无人机数据' }}
        </el-descriptions-item>
        <el-descriptions-item label="区域">{{ formatAreaName(currentLayer.area) }}</el-descriptions-item>
        <el-descriptions-item label="WMS地址">{{ currentLayer.wmsUrl }}</el-descriptions-item>
        <el-descriptions-item label="图层名称">{{ currentLayer.layerName }}</el-descriptions-item>
        <el-descriptions-item label="文件夹类型">{{ currentLayer.folderType }}</el-descriptions-item>
      </el-descriptions>
    </el-drawer>
  </el-card>

</template>

<script setup>
import { ref, onMounted } from 'vue'
import {mapLayerListService, publishLayerService} from "@/api/map";
import { ElMessage } from "element-plus";

// 地图服务列表数据
const layerList = ref([])
// 加载状态
const loading = ref(false)

// 分页相关
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)
const queryForm = ref({
  area: '',    // 区域查询条件（非必需）
  date: ''     // 日期查询条件（非必需，格式yyyy-MM-dd）
})
// 获取地图服务列表
const getLayerList = async () => {
  try {
    loading.value = true
    const result = await mapLayerListService({
      pageNum: currentPage.value,
      pageSize: pageSize.value,
      ...queryForm.value
    })
    layerList.value = result.data.items
    total.value = result.data.total
  } catch (error) {
    ElMessage.error('获取地图服务列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}
const handleQuery = () => {
  currentPage.value = 1  // 查询时重置为第一页
  getLayerList()
}

const resetQuery = () => {
  queryForm.value = {  // 清空查询条件
    area: '',
    date: ''
  }
  currentPage.value = 1
  getLayerList()
}
// 引入查看图标
import {  View } from '@element-plus/icons-vue'

// 详情相关变量
const detailDrawer = ref(false)
const currentLayer = ref({})

// 区域名称格式化（复用预警监控页面的映射关系）
const areaMap = {
  hadawan: '哈达湾',
  niaodao: '鸟岛',
  buhahekouhaibeiqu: '布哈河口海北区',
  buhahekouhainanqu: '布哈河口海南区',
  quanwan: '泉湾',
  heimahekou: '黑马河口',
  erlangjian: '二郎剑',
  qinghaihu: '青海湖'
}

const formatAreaName = (pinyin) => {
  return areaMap[pinyin] || pinyin
}

// 查看详情操作
const handleView = (row) => {
  currentLayer.value = { ...row }
  detailDrawer.value = true
}
// 页面加载时获取数据
onMounted(() => {
  getLayerList()
})
// 新增引入编辑图标
import { Plus, Edit, Delete } from '@element-plus/icons-vue'
import { mapLayerUpdateService, mapLayerDeleteService } from "@/api/map";
import {  ElMessageBox } from "element-plus";

// 新增编辑相关变量
const editDrawer = ref(false)
const editFormRef = ref(null)
const editFormData = ref({
  id: '',
  date: '',
  type: '',
  area: '',
  // 其他需要编辑的字段
})

// 编辑操作
const handleEdit = (row) => {
  // 打开编辑抽屉并回显数据
  editFormData.value = { ...row }
  editDrawer.value = true
}

// 保存编辑
const handleUpdate = async () => {
  try {
    await editFormRef.value.validate()
    await mapLayerUpdateService(editFormData.value)
    ElMessage.success('修改成功')
    editDrawer.value = false
    getLayerList()
  } catch (error) {
    if (error.name !== 'ValidationError') {
      ElMessage.error('修改失败')
    }
  }
}

// 删除操作
const handleDelete = (row) => {
  ElMessageBox.confirm(
      '确认删除该地图服务吗？',
      '温馨提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }
  ).then(async () => {
    try {
      await mapLayerDeleteService(row.id)
      ElMessage.success('删除成功')
      getLayerList()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  })
}
// 分页事件处理
const handlePageChange = (page) => {
  currentPage.value = page
  getLayerList()
}

const handleSizeChange = (size) => {
  pageSize.value = size
  currentPage.value = 1
  getLayerList()
}
// 发布地图相关变量
const publishDrawer = ref(false); // 控制抽屉显示
const publishFormRef = ref(null);
const formData = ref({
  date: '', // 格式：yyyy-MM-dd
  type: '', // satellite/drone
  area: ''  // 仅drone类型需要
});

// 表单验证规则
const rules = {
  date: [
    { required: true, message: '请选择日期', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择数据源类型', trigger: 'change' }
  ],
  area: [
    { required: true, message: '请选择区域', trigger: 'change' }
  ]
};

// 打开发布抽屉
const openPublishDrawer = () => {
  publishDrawer.value = true;
  formData.value = { date: '', type: '', area: '' }; // 重置表单
};

// 提交发布
const handlePublish = async () => {
  // 表单验证
  const valid = await publishFormRef.value.validate();
  if (!valid) return;

  try {
    await publishLayerService(formData.value);
    ElMessage.success('地图服务发布成功');
    publishDrawer.value = false;
    await getLayerList(); // 刷新列表
  } catch (error) {
    ElMessage.error('发布失败：' + (error.message || '未知错误'));
  }
};
</script>

<style scoped>
.page-container {
  min-height: 100%;
  box-sizing: border-box;
  padding: 20px;
}

.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-bottom: 20px;
}
.query-form {
  padding: 10px 0;
  background-color: #f5f7fa;
  border-radius: 4px;
  padding-left: 16px;
}
</style>